import logging
import yaml

class AttrData(object):
	def __init__(self, yaml_str = ''):
		self.__yaml_str = yaml_str

	def set_attribute(self, name, value):
		"""Create or replace an attribute."""
		data = yaml.load(self.__yaml_str)
		data = {} if data is None else data

		data[name] = value
		self.__yaml_str = yaml.safe_dump(data)

	def delete_attribute(self, name):
		data = yaml.load(self.__yaml_str)
		data = {} if data is None else data

		try:
			del data[name]
		except KeyError:
			logging.warning("AttrData.delete_attribute(): trying to delete a nonexistent attribute '%s'" % name)

		self.__yaml_str = yaml.safe_dump(data)
		
	def get_attribute(self, name):
		data = yaml.load(self.__yaml_str)
		data = {} if data is None else data

		try:
			return data[name]
		except KeyError:
			logging.warning("AttrData.get_attribute(): trying to get a nonexistent attribute '%s'" % name)
			return None

	def to_string(self):
		return self.__yaml_str

